package com.xiguaji.tiktok.task.aweme.event;

import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;
import com.gugee.tiktok.common.model.AwemeScore;
import com.gugee.tiktok.common.model.dal.blogger.AwemeRepository;
import com.gugee.tiktok.common.model.mysql.Aweme;
import com.xiguaji.boot.eventbus.Event;
import com.xiguaji.boot.eventbus.IEventListener;
import com.xiguaji.boot.toolkit.DateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class SetAwemeScoreEventListener implements IEventListener<SetAwemeScoreEventListener.SetAwemeScoreEvent> {

    @Autowired
    AwemeRepository awemeRepository;

    @Override
    @Subscribe
    @AllowConcurrentEvents
    public void handle(SetAwemeScoreEvent event) {
        List<Aweme> awemeList = awemeRepository.findAwemesByoUidAndoCreateTimeGreaterThan(
                event.tikTokScore.getBloggerMain().getOUid(),
                DateTimeUtils.second(LocalDateTime.now().minusDays(90)));

        awemeList.forEach(a ->{
            a.setScore(event.tikTokScore.getAwemeScore(a));
            a.setUpdateBy("GetAwemeScoreEvent");
        });

        if(awemeList.size() > 0){
            long start = System.currentTimeMillis();
            awemeRepository.batchUpdate(awemeList);
            if((System.currentTimeMillis()-start)/1000 >5)
                log.info("SetAwemeScoreEventListener batchUpdate count:"+awemeList.size()+" use time:"+(System.currentTimeMillis()-start)/1000+"s");

            event.tikTokScore.getBloggerMain().setLastCollectTime(new Date());
        }

    }

    public static class SetAwemeScoreEvent extends Event{

        public SetAwemeScoreEvent(AwemeScore tikTokScore) {
            super("GetAwemeScoreEvent");
            this.tikTokScore = tikTokScore;
        }

        AwemeScore tikTokScore;
    }
}
